
/*#
# Copyright 2012 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This code is not supported by Google
#
*/
/**
 * Sample application for Google Commerce Search.
 * http://www.google.com/commercesearch/
 * 
 * This app performs a GCS query against the Google Store products
 * (www.googlestore.com) and displays the first 10 results  You can substitute 
 * your own GCS instanceID and API key by configuring the 'settings' section. 
 */
package com.google.enterprise.gcs.search;

import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.shopping.Shopping;
import com.google.api.services.shopping.model.Product;
import com.google.api.services.shopping.model.Products;
import com.google.enterprise.gcs.search.R;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class GCSSearch extends Activity {
	private static final String LOGGING_TAG = "GCSSearch"; 
	
    public Activity a;
    public ItemAdapter adapter;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        a = this;
        PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
        
        EditText etsearch = (EditText) findViewById(R.id.searchText1);
        etsearch.setOnKeyListener(new OnKeyListener()  {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event)   {
                if (event.getAction() == KeyEvent.ACTION_DOWN)   {
                    switch (keyCode)   {
                        case KeyEvent.KEYCODE_ENTER:
                            getResults(getWindow().getDecorView().findViewById(android.R.id.content));
                            return true;
                        default:
                            break;
                    }
                }
                return false;
            }
        });        
    }
    
    public void getResults(View view)
    {
        RunQuery task = new RunQuery();
        EditText mEdit   = (EditText)findViewById(R.id.searchText1);
        Log.i(LOGGING_TAG, "getResults Query [" + mEdit.getText().toString() + "]");        
        task.execute(mEdit.getText().toString());        
    } 
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {     
    	Intent intent = new Intent();
        switch (item.getItemId()) {
        case R.id.menu_settings:
            intent.setClass(this, SetPreferencesActivity.class);
            startActivityForResult(intent, 0);
            return true;
        case R.id.help:
        	openOptionsHelpDialog(); 
        	return false;
        }
        return false;
    } 
    
    private void openOptionsHelpDialog()
    {
     new AlertDialog.Builder(this)
     .setTitle(R.string.help_settings).setMessage(R.string.help_message)
     .setPositiveButton(R.string.btn_ok, new DialogInterface.OnClickListener() {       
       @Override
       public void onClick(DialogInterface dialog, int which) {     
       }}).show();
    }    
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
    	super.onCreateOptionsMenu(menu);
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.menu, menu);
    	return true;
    }
 
    private class RunQuery extends AsyncTask<String, Void, Products> {
      @Override
      protected Products doInBackground(String... params) {
          
    	  // Using Google APIs library for Search API for Shopping for simplicity.
    	  // The API libraries are not supported by Google Enterprise. 
    	  // https://developers.google.com/shopping-search/libraries
          HttpTransport transport = new NetHttpTransport(); 
          JsonFactory json_factory = new JacksonFactory();
          Shopping.Builder sb = Shopping.builder(transport, json_factory);
          String query = params[0];
          
          SharedPreferences mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(a);
          
          String cx_preference = mySharedPreferences.getString("cx_preference", "");
          Log.i(LOGGING_TAG,"Using cx: " + cx_preference);
          
          String key_preference = mySharedPreferences.getString("key_preference", "");
          Log.i(LOGGING_TAG,"Using key: " + key_preference);
          
          String country_preference = mySharedPreferences.getString("country_preference", "");
          Log.i(LOGGING_TAG,"Using country: " + country_preference);          

          try
          {
          Shopping shopping = sb.build(); 
          Shopping.Products.List req = shopping.products().list("cx:" + cx_preference)
          .setQ(query)
          .setCountry(country_preference)
          .setMaxResults(10L)
          .setSafe(false);
          req.setKey(key_preference);
                         
          Products ps = req.execute();           

          return ps;
          }
         
          catch (Exception ex)
          {
              Log.v(LOGGING_TAG, "RunQuery " + ex.toString());
          }
          return null;
      }
      
      @Override
      protected void onPostExecute(Products ps) {           
        
    	if (ps == null) {
    		new AlertDialog.Builder(a)
    	    .setTitle("Error")
    	    .setMessage("Please check network connectivity and the cx, api key and country configuration.")
    	    .setPositiveButton(R.string.btn_ok, new DialogInterface.OnClickListener() {
    	        @Override
              public void onClick(DialogInterface dialog, int which) { 
    	        	Intent intent = new Intent();
    	            intent.setClass(a, SetPreferencesActivity.class);
    	            startActivityForResult(intent, 0);
    	        }
    	     }).show();
            return;
    	}
    		
    		
        Toast.makeText(getApplicationContext(), "Total Results: " + ps.getTotalItems().toString(), Toast.LENGTH_SHORT).show(); 
        Log.i("GCSSearch onPostExecute", "Total Results  " + ps.getTotalItems().toString()); 
      	ArrayList<ListItem> results = new ArrayList<ListItem>();

          if (ps.getTotalItems() > 0)
            for (Product p : ps.getItems()) {
            	// TODO: somehow pass in entire 'com.google.api.services.shopping.model.Product'
            	// object into the Listitem parcel and not have get/set methods for each property

              	ListItem item_details = new ListItem();
              	item_details.setTitle(p.getProduct().getTitle());
              	item_details.setPrice(p.getProduct().getInventories().get(0).getCurrency() + " " + 
              					      p.getProduct().getInventories().get(0).getPrice().toString());
        		item_details.setImageURL(p.getProduct().getImages().get(0).getLink());
        		item_details.setItemDescription(p.getProduct().getDescription());
        		item_details.setOfferURL(p.getProduct().getLink());
              	results.add(item_details);
            }   
          
      	final ListView lv1 = (ListView) findViewById(R.id.ListViewId);
      	
        lv1.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            	TextView tvtitle = (TextView) view.findViewById(R.id.title);
                String title = tvtitle.getText().toString();
                Intent i = new Intent(a, ItemDetail.class);
                i.putExtra("title", title);
                ListItem item = adapter.getItem(position);
                i.putExtra("item", item);
                startActivity(i);
            }
          });      	
        adapter = new ItemAdapter(a, R.layout.listitem, results);
        lv1.setAdapter(adapter);
            	          
      }      
      
    }
   
}